﻿/*  ----------------------------------------------------------------------------
 *  DES-Release 2
 *  ----------------------------------------------------------------------------
 *  File:       Form2.cs
 *  Author:     nitinkoshy@gmail.com
 *  Source:     http://des.codeplex.com/
 *  ----------------------------------------------------------------------------
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Security.Principal;
using System.Net.Sockets;
using System.Net;
using System.Net.Security;

namespace DES.Test
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            WindowsPrincipal alice = SSPIHelperV1.LogonUser("tester", "blrkec37146l", "W1nd0w*V1*ta");
            MessageBox.Show(alice.Identity.Name);
        }


    }
    public class SSPIHelperV1
    {
        public static WindowsPrincipal LogonUser(string userName, string domain, string password)
        {
            // need a full duplex stream - loopback is easiest way to get that
            TcpListener tcpListener = new TcpListener(IPAddress.Loopback, 0);
            tcpListener.Start();


            WindowsIdentity id = null;
            IAsyncResult serverResult = tcpListener.BeginAcceptTcpClient(delegate(IAsyncResult asyncResult)
            {
                using (NegotiateStream serverSide = new NegotiateStream(
                         tcpListener.EndAcceptTcpClient(asyncResult).GetStream()))
                {
                    serverSide.AuthenticateAsServer(CredentialCache.DefaultNetworkCredentials,
                         ProtectionLevel.None, TokenImpersonationLevel.Impersonation);
                    id = (WindowsIdentity)serverSide.RemoteIdentity;
                }
            }, null);


            using (NegotiateStream clientSide = new NegotiateStream(new TcpClient("localhost",
                         ((IPEndPoint)tcpListener.LocalEndpoint).Port).GetStream()))
            {
                clientSide.AuthenticateAsClient(new NetworkCredential(userName, password, domain),
                         "", ProtectionLevel.None, TokenImpersonationLevel.Impersonation);
            }

            while (id==null) ;

            return new WindowsPrincipal(id);
        }
    }

}
